package com.asus.oplay.asusuitest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;

import org.apache.http.util.EncodingUtils;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.os.SystemProperties;

public class ASUSUITest extends Activity implements
CompoundButton.OnCheckedChangeListener {

    private static final int  INIT = 0;
    private static final int  IR = INIT+1;
    private static final int  VIDEO =IR +1 ;
    private static final int  USB = VIDEO +1;
    private static final int  LAN = USB+1;
    private static final int  WLAN = -8;
    private static final int  WRSSI = -9;
    private static final int  BLUETOOTH = LAN+1;
    private static final int  LIVETV = -3;
    private static final int  IRB = -4;
    private static final int  MAC = BLUETOOTH+1;
    private static final int  BUILD = MAC+1;
    private static final int  MCUVER = BUILD + 1;
    private static final int  SHARE = -5;

    private static final int  AUDIO = -6;
    private static final int  PHOTO = -7;

    private static final int  TESTFINISH = MCUVER+1;
    private static final int  ERROR = -1;
    private int m_Status = INIT;

    private String TAG = "ASUSUITest";
    private String usbmedia="";
    private String usblog="";
    private String usbconfig="";
    private CheckBox checkboxbutton;
    private Activity mactivity;
    private String testtitle;
    private String macstring = null;
    private WifiManager Wifimanager;
    private BluetoothAdapter mAdapter;
    private ProgressDialog mSpinner;
    private boolean AutoCheck;
    private boolean ManualCheck;
    private boolean FirstIRBTest;

    private String videofile="";
    private String audiofile="";
    private String photofile="";
    //private String lanfile="";
    private String wlanfile="";
    private String btfile="";
    private String wifistrength="";
    private String buildfile="";
    private String mcuverfile="";
    private String modefile="";

    private String macbeg="";
    private String macend="";
    private String apkfile="";

    //static {
    //	System.loadLibrary("oplayirb");
    //}

    private native int DoIRBTest();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_asusuitest);

        String versionName = "";
        String APName = "";
        
        final Version version = new Version(this);	////sonic for test
        
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            versionName = pi.versionName;
            APName = (String) pm.getApplicationLabel(pi.applicationInfo);
            if(versionName == null || versionName.length() <= 0)
                versionName = "";
            if(APName == null || APName.length() <= 0)
                APName = "ASUSUITest";
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.i(TAG,versionName);

        setTitle(APName + "  V" + versionName);

        Wifimanager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        if(!Wifimanager.isWifiEnabled())
            Wifimanager.setWifiEnabled(true);

        mAdapter= BluetoothAdapter.getDefaultAdapter();
        if(!mAdapter.isEnabled())
            mAdapter.enable();

        mSpinner = new ProgressDialog(this);
        mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		mSpinner.setMessage("Bluetooth search...");
        mSpinner.setMessage("蓝牙搜寻中...");

        if(this.getIntent() != null && this.getIntent().getExtras() != null)
        {
            usbmedia = this.getIntent().getExtras().getString("usbmedia");
            usblog = this.getIntent().getExtras().getString("usblog");
            usbconfig = this.getIntent().getExtras().getString("usbconfig");
        }

        mactivity = this;
        AutoCheck = false;
        ManualCheck = false;
        FirstIRBTest = true;

        DisableAll();

//        Button test = (Button) findViewById(R.id.buttonfinish);
//
//        test.setOnClickListener(new OnClickListener() {
//            public void onClick(View v) {
//                SaveLogFile();
//                if(CheckAllTest(true))
//                    ErrorMessage("All Pass !");
//                else
//                    ErrorMessage("Test fail !");
//            }
//        });
        
        ////sonic for test
        Button test = (Button) findViewById(R.id.buttonfinish);

        test.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	version.Refresh();
				final String VerSion = Environment
						.getExternalStorageDirectory().getPath()
						+ "/test目录下的apk："
						+ "\n"
						+ version.getFileApkCode()
						+ "\n"
						+ "能够更新的有"
						+ version.flag
						+ "个！分别是："
						+ "\n"
						+ version.getCanUpdate();
				ErrorMessage(VerSion);
            }
        });
        ////sonic for test
        

        BroadcastReceiver mReceiver = new BroadcastReceiver() {

            boolean bfound = false;
            public void onReceive(Context context, Intent intent) {

                Log.i(TAG,"modefile:"+modefile);
                Log.i(TAG,"m_Status:"+m_Status);
                if(!modefile.equalsIgnoreCase("PRODUCT"))
                    return;

                if(m_Status != BLUETOOTH)
                    return;

                if(bfound)
                {
                    Log.i(TAG,"Found device last time.");
                    return;
                }
                String action = intent.getAction();


                if (BluetoothDevice.ACTION_FOUND.equals(action)) {

                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

                        Log.i(TAG, "find bluetooth device:" + device.getName() + " "+ device.getAddress() + " / " + btfile);
                        if(device.getAddress().equalsIgnoreCase(btfile))
                        {
                            String str = (String) ((CheckBox)findViewById(R.id.checkboxBluetooth)).getText();
                            str = str.replace(" Fail", "");
                            str = str.replace(" Test", "");

                            AutoCheck = true;
                            ((CheckBox)findViewById(R.id.checkboxBluetooth)).setText(str + " Pass");
                            ((CheckBox)findViewById(R.id.checkboxBluetooth)).setTextColor(Color.BLUE);
                            ((CheckBox)findViewById(R.id.checkboxBluetooth)).setChecked(true);
                            bfound = true;
                            mSpinner.dismiss();

                            if(ManualCheck)
                                CheckAllTest(false);
                            else
                                CallTestFunction(true);
                        }
                    }

                }
                else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    Log.i(TAG,"no find bluetooth device");

                    String str = (String) ((CheckBox)findViewById(R.id.checkboxBluetooth)).getText();
                    str = str.replace(" Fail", "");
                    str = str.replace(" Test", "");
                    ((CheckBox)findViewById(R.id.checkboxBluetooth)).setText(str + " Fail");
                    ((CheckBox)findViewById(R.id.checkboxBluetooth)).setTextColor(Color.RED);

                    mSpinner.dismiss();

                    TestErrorInfo("蓝牙测试失败,再试一次?");
                }
            }
        };


        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);

        ((CheckBox)findViewById(R.id.checkboxVideo)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxAudio)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxPhoto)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxLivetv)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxBluetooth)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxLan)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxWLan)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxWRSSI)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxIR)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxIRB)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxShare)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxMac)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxUSB)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxBuild)).setOnCheckedChangeListener(this);
        ((CheckBox)findViewById(R.id.checkboxMCUVER)).setOnCheckedChangeListener(this);
    }

    //	@Override
    //	public boolean onCreateOptionsMenu(Menu menu) {
    //		getMenuInflater().inflate(R.menu.activity_asusuitest, menu);
    //		return true;
    //	}

    public void onCheckedChanged(CompoundButton view,boolean ischecked)
    {
        if(ischecked)
            Log.i(TAG,"onCheckedChanged ischecked: true");
        else
            Log.i(TAG,"onCheckedChanged ischecked: false");

        if(AutoCheck)
        {
            AutoCheck = false;
            return;
        }

        if(ischecked)
        {
            view.setChecked(false);
            if(view.getId() == R.id.checkboxVideo)
                m_Status = VIDEO;

            if(view.getId() == R.id.checkboxUSB)
                m_Status = USB;

            if(view.getId() == R.id.checkboxAudio)
                m_Status = AUDIO;

            if(view.getId() == R.id.checkboxPhoto)
                m_Status = PHOTO;

            if(view.getId() == R.id.checkboxLivetv)
                m_Status = LIVETV;

            if(view.getId() == R.id.checkboxBluetooth)
                m_Status = BLUETOOTH;

            if(view.getId() == R.id.checkboxLan)
                m_Status = LAN;

            if(view.getId() == R.id.checkboxWLan)
                m_Status = WLAN;

            if(view.getId() == R.id.checkboxWRSSI)
                m_Status = WRSSI;

            if(view.getId() == R.id.checkboxIR)
                m_Status = IR;

            if(view.getId() == R.id.checkboxIRB)
                m_Status = IRB;

            if(view.getId() == R.id.checkboxShare)
                m_Status = SHARE;

            if(view.getId() == R.id.checkboxMac)
                m_Status = MAC;

            if(view.getId() == R.id.checkboxBuild)
                m_Status = BUILD;

            if(view.getId() == R.id.checkboxMCUVER)
                m_Status = MCUVER;

            ManualCheck = true;

            CallTestFunction(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
        //SaveLogFile();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG,"onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,"onResume:"+Integer.toString(m_Status));
        switch(m_Status)
        {
        case INIT:
            Log.i(TAG,"onResume:INIT");
            if(CheckMediaFileSystem() && CheckLogFileSystem() && CheckConfigFileSystem())
            {
                if(ManualCheck)
                    CheckAllTest(false);
                else
                    CallTestFunction(true);
            }
            break;
        case VIDEO:
        case AUDIO:
        case PHOTO:
        //case LIVETV:
        //case BLUETOOTH:
        //case LAN:
        //case WLAN:
            //case WRSSI:
            //case IR:
        //case IRB:
        case SHARE:
        //case MAC:
        //case USB:
            AlertMessage();
            break;
        default:
            return;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG,"onStop");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,"onStart");
    }

    private void StartVideoTest()
    {
        File  file = new File(usbmedia+".factorymode_media/"+videofile);

        Log.d(TAG,"test==videofile="+videofile);

        //File file = new File(usbpath+".factorymode_media/MP4/");
        if(file!=null && file.exists())
        {
            //File[] filelist = file.listFiles();
            //if(filelist.length > 0)
            {
                Intent it = new Intent(Intent.ACTION_VIEW);
                //it.setDataAndType(Uri.parse("file://"+filelist[0].getPath()), "video/avi");
                it.setDataAndType(Uri.parse("file://"+file.getPath()), "video/avi");
                startActivity(it);
                m_Status = VIDEO;
                return;
            }
        }

        m_Status = ERROR;
        ErrorMessage("MP4文件错误，请检查Media U盘.");
    }

    private void StartAudioTest()
    {
        File  file = new File(usbmedia+".factorymode_media/"+audiofile);
        //File file = new File(usbpath+".factorymode_media/MP3/");
        if(file!=null && file.exists())
        {
            //File[] filelist = file.listFiles();

            //if(filelist.length > 0)
            {
                Intent it = new Intent(Intent.ACTION_VIEW);
                //it.setDataAndType(Uri.parse("file://"+filelist[0].getPath()), "audio/mp3");
                it.setDataAndType(Uri.parse("file://"+file.getPath()), "audio/mp3");
                startActivity(it);
                m_Status = AUDIO;
                return;
            }
        }

        m_Status = ERROR;
        ErrorMessage("MP3文件错误，请检查Media U盘.");
    }
    
    ////sonic for test
    private void StartApkInstallTest()
    {
    	Log.d(TAG,"sonic==test==StartApkInstallTest");
        File  file = new File(usbmedia+".factorymode_install/"+apkfile);
        //File file = new File(usbpath+".factorymode_media/MP3/");
        if(file!=null && file.exists())
        {
            //File[] filelist = file.listFiles();

            //if(filelist.length > 0)
            {
                Intent it = new Intent(Intent.ACTION_VIEW);
                //it.setDataAndType(Uri.parse("file://"+filelist[0].getPath()), "audio/mp3");
                it.setDataAndType(Uri.parse("file://"+file.getPath()), "application/vnd.android.package-archive");
                startActivity(it);
//                m_Status = AUDIO;
                return;
            }
        }

        m_Status = ERROR;
        ErrorMessage("APK文件错误，请检查Media U盘.");
    }

	public static void InstallAPK(Context c, File f) 
	{
		Intent promptInstall = new Intent(Intent.ACTION_VIEW);
		promptInstall.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");

		try {
			c.startActivity(promptInstall);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(c.getApplicationContext(), "install error", Toast.LENGTH_SHORT).show();
		}
	}
	////sonic for test

    private void StartPhotoTest()
    {
        File  file = new File(usbmedia+".factorymode_media/"+photofile);
        //File file = new File(usbpath+".factorymode_media/JPG/");
        if(file!=null && file.exists())
        {
            //File[] filelist = file.listFiles();

            //if(filelist.length > 0)
            {
                Intent it = new Intent(Intent.ACTION_VIEW);
                //it.setDataAndType(Uri.parse("file://"+filelist[0].getPath()), "image/jpg");
                it.setDataAndType(Uri.parse("file://"+file.getPath()), "image/jpg");
                startActivity(it);
                m_Status = PHOTO;
                return;
            }
        }

        m_Status = ERROR;
        ErrorMessage("JPG文件错误，请检查Media U盘.");
    }

    private void StartUSBTest()
    {
        boolean bcheck = false;
        String str = (String) ((CheckBox)findViewById(R.id.checkboxUSB)).getText();
        str = str.replace(" Fail", "");
        str = str.replace(" Test", "");

        if(usblog == null || usblog.equalsIgnoreCase("") == true
                || usbmedia == null || usbmedia.equalsIgnoreCase("") == true
                || usbconfig == null || usbconfig.equalsIgnoreCase("") == true)
        {
            ((CheckBox)findViewById(R.id.checkboxUSB)).setText(str + " Fail");
            ((CheckBox)findViewById(R.id.checkboxUSB)).setTextColor(Color.RED);
            TestErrorInfo("测试USB接口错误,再试一次?");
        }

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy:MM:dd:hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        date = date.replace(":", "");
        String strfiletest = "test";
        if(date != null)
            strfiletest = date;
        File filetest = new File(usblog+strfiletest);
        String errstr="";
        filetest.mkdir();
        if(filetest.exists())
        {
            filetest.delete();
            bcheck = true;
        }
        else
        {
            bcheck = false;
            errstr = "Log USB";
        }

        if(bcheck)
        {
            File filetest1 = new File(usbmedia+strfiletest);
            filetest1.mkdir();
            if(filetest1.exists())
            {
                filetest1.delete();
                bcheck = true;
            }
            else
            {
                bcheck = false;
                errstr = "Media USB";
            }
        }

        if(bcheck)
        {
            File filetest2 = new File(usbconfig+strfiletest);
            filetest2.mkdir();
            if(filetest2.exists())
            {
                filetest2.delete();
                bcheck = true;
            }
            else
            {
                bcheck = false;
                errstr = "Config USB";
            }
        }

        if(bcheck)
        {
            AutoCheck = true;
            ((CheckBox)findViewById(R.id.checkboxUSB)).setText(str + " Pass");
            ((CheckBox)findViewById(R.id.checkboxUSB)).setTextColor(Color.BLUE);
            ((CheckBox)findViewById(R.id.checkboxUSB)).setChecked(true);
            if(ManualCheck)
                CheckAllTest(false);
            else
                CallTestFunction(true);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxUSB)).setText(str + " Fail");
            ((CheckBox)findViewById(R.id.checkboxUSB)).setTextColor(Color.RED);
            TestErrorInfo("测试 "+errstr +" 错误 ,再试一次?");
        }
    }

    private void StartLanTest()
    {
        //		Intent mIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
        //		mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        //		startActivity(mIntent);
        ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo ethInfo = conMan.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);

        String str = (String) ((CheckBox)findViewById(R.id.checkboxLan)).getText();
        str = str.replace(" Fail", "");
        str = str.replace(" Test", "");

        if(conMan != null && ethInfo != null)
        {
            //State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).getState();
            //Log.i(TAG, "ethernet status " + mobile.toString());
            if(ethInfo.isConnected())
            {
                    AutoCheck = true;
                    ((CheckBox)findViewById(R.id.checkboxLan)).setText(str + " Pass");
                    ((CheckBox)findViewById(R.id.checkboxLan)).setTextColor(Color.BLUE);
                    ((CheckBox)findViewById(R.id.checkboxLan)).setChecked(true);
                    if(ManualCheck)
                        CheckAllTest(false);
                    else
                        CallTestFunction(true);
                    return;
            }else
                Log.i(TAG, "Ethernet is not connected");
        }else
            Log.i(TAG, "Fail to get ethernet status !! ");

        ((CheckBox)findViewById(R.id.checkboxLan)).setText(str + " Fail");
        ((CheckBox)findViewById(R.id.checkboxLan)).setTextColor(Color.RED);

//		TestErrorInfo("Test Lan Error,try it again?");
        TestErrorInfo("测试有线网络失败,再试一次?");
    }

    private void StartWLanTest()
    {
//		mSpinner.setMessage("WLan search...");
        mSpinner.setMessage("无线网卡WLan 搜寻中...");
        mSpinner.show();

        if(!Wifimanager.isWifiEnabled())
            Wifimanager.setWifiEnabled(true);

        WifiConfiguration wc = new WifiConfiguration();

        wc.allowedAuthAlgorithms.clear();
        wc.allowedGroupCiphers.clear();
        wc.allowedKeyManagement.clear();
        wc.allowedProtocols.clear();
        wc.allowedPairwiseCiphers.clear();

        wc.SSID = "\""+ wlanfile +"\"";
        wc.wepKeys[0] = "";
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wc.wepTxKeyIndex = 0;

        int res = Wifimanager.addNetwork(wc);

        if(Wifimanager.enableNetwork(res, false) == true)
            Log.i(TAG,"enableNetwork OK");
        else
            Log.i(TAG,"enableNetwork Error");

        new Thread()
        {
            @Override public void run()
            {
                try
                {
                    //int wifi = Integer.parseInt(wifistrength);
                    for(int i=0;i<50;i++)
                    {
                        sleep(1000);
                        ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                        //					String str = (String) ((CheckBox)findViewById(R.id.checkboxWLan)).getText();
                        //					str = str.replace(" Fail", "");
                        //					str = str.replace(" Test", "");

                        if(conMan != null && conMan.getActiveNetworkInfo() != null)
                        {
                            android.net.NetworkInfo.State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
                            if(mobile != null)
                            {
                                if(mobile.toString().equalsIgnoreCase("CONNECTED"))
                                {
                                    //int strength = WifiManager.calculateSignalLevel(Wifimanager.getConnectionInfo().getRssi(), 100);
                                    //int speed = Wifimanager.getConnectionInfo().getLinkSpeed();
                                    //Log.e(TAG,Integer.toString(strength) + " " + Integer.toString(speed));
                                    //Log.e(TAG,Integer.toString(strength) + " " + Integer.toString(wifi));

                                    //if(strength > wifi)
                                    {
                                        mactivity.runOnUiThread(new Runnable() {
                                            public void run() {
                                                String str = (String) ((CheckBox)findViewById(R.id.checkboxWLan)).getText();
                                                str = str.replace(" Fail", "");
                                                str = str.replace(" Test", "");

                                                mSpinner.dismiss();

                                                AutoCheck = true;
                                                ((CheckBox)findViewById(R.id.checkboxWLan)).setText(str + " Pass");
                                                ((CheckBox)findViewById(R.id.checkboxWLan)).setTextColor(Color.BLUE);
                                                ((CheckBox)findViewById(R.id.checkboxWLan)).setChecked(true);
                                                if(ManualCheck)
                                                    CheckAllTest(false);
                                                else
                                                    CallTestFunction(true);
                                            }
                                        });
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (InterruptedException e)
                {
                    System.out.println("Sleep interrupted");
                    e.printStackTrace();
                }

                mactivity.runOnUiThread(new Runnable() {
                    public void run() {
                        String str = (String) ((CheckBox)findViewById(R.id.checkboxWLan)).getText();
                        str = str.replace(" Fail", "");
                        str = str.replace(" Test", "");
                        ((CheckBox)findViewById(R.id.checkboxWLan)).setText(str + " Fail");
                        ((CheckBox)findViewById(R.id.checkboxWLan)).setTextColor(Color.RED);

                        mSpinner.dismiss();
                        TestErrorInfo("测试无线网卡失败,再试一次?");
                    }
                });
            }
        }.start();

        //		ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //
        //		String str = (String) ((CheckBox)findViewById(R.id.checkboxWLan)).getText();
        //		str = str.replace(" Fail", "");
        //		str = str.replace(" Test", "");
        //
        //		if(conMan != null && conMan.getActiveNetworkInfo() != null)
        //		{
        //			State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        //			if(mobile != null)
        //			{
        //				if(mobile.toString().equalsIgnoreCase("CONNECTED"))
        //				{
        //					AutoCheck = true;
        //					((CheckBox)findViewById(R.id.checkboxWLan)).setText(str + " Pass");
        //					((CheckBox)findViewById(R.id.checkboxWLan)).setTextColor(Color.BLUE);
        //					((CheckBox)findViewById(R.id.checkboxWLan)).setChecked(true);
        //					if(ManualCheck)
        //						CheckAllTest(false);
        //					else
        //						CallTestFunction(true);
        //
        //					mSpinner.dismiss();
        //					return;
        //				}
        //			}
        //		}

        //		((CheckBox)findViewById(R.id.checkboxWLan)).setText(str + " Fail");
        //		((CheckBox)findViewById(R.id.checkboxWLan)).setTextColor(Color.RED);
        //
        //		mSpinner.dismiss();
        //		TestErrorInfo("Test WLan Error,try it again?");
    }

    private void StartWRSSITest()
    {
        if(((CheckBox)findViewById(R.id.checkboxWLan)).isChecked())
        {
//			mSpinner.setMessage("WRSSI search...");
            mSpinner.setMessage("WRSSI(Wifi信号强度) 搜寻中...");
            mSpinner.show();

            new Thread()
            {
                @Override public void run()
                {
                    try
                    {
                        int wifi = Integer.parseInt(wifistrength);
                        for(int i=0;i<20;i++)
                        {
                            sleep(1000);
                            ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                            if(conMan != null && conMan.getActiveNetworkInfo() != null)
                            {
                                android.net.NetworkInfo.State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
                                if(mobile != null)
                                {
                                    if(mobile.toString().equalsIgnoreCase("CONNECTED"))
                                    {
                                        int strength = WifiManager.calculateSignalLevel(Wifimanager.getConnectionInfo().getRssi(), 100);
                                        Log.e(TAG,Integer.toString(strength) + " " + Integer.toString(wifi));

                                        if(strength > wifi)
                                        {
                                            mactivity.runOnUiThread(new Runnable() {
                                                public void run() {
                                                    String str = (String) ((CheckBox)findViewById(R.id.checkboxWRSSI)).getText();
                                                    str = str.replace(" Fail", "");
                                                    str = str.replace(" Test", "");

                                                    mSpinner.dismiss();

                                                    AutoCheck = true;
                                                    ((CheckBox)findViewById(R.id.checkboxWRSSI)).setText(str + " Pass");
                                                    ((CheckBox)findViewById(R.id.checkboxWRSSI)).setTextColor(Color.BLUE);
                                                    ((CheckBox)findViewById(R.id.checkboxWRSSI)).setChecked(true);
                                                    if(ManualCheck)
                                                        CheckAllTest(false);
                                                    else
                                                        CallTestFunction(true);
                                                }
                                            });
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (InterruptedException e)
                    {
                        System.out.println("Sleep interrupted");
                        e.printStackTrace();
                    }

                    mactivity.runOnUiThread(new Runnable() {
                        public void run() {
                            String str = (String) ((CheckBox)findViewById(R.id.checkboxWRSSI)).getText();
                            str = str.replace(" Fail", "");
                            str = str.replace(" Test", "");
                            ((CheckBox)findViewById(R.id.checkboxWRSSI)).setText(str + " Fail");
                            ((CheckBox)findViewById(R.id.checkboxWRSSI)).setTextColor(Color.RED);

                            mSpinner.dismiss();
                            TestErrorInfo("Test WRSSI Error,再试一次?");
                        }
                    });
                }
            }.start();
        }
        else
        {
            //Log.i(TAG,"Test WLAN Pass First.");

            String str = (String) ((CheckBox)findViewById(R.id.checkboxWRSSI)).getText();
            str = str.replace(" Fail", "");
            str = str.replace(" Test", "");

            ((CheckBox)findViewById(R.id.checkboxWRSSI)).setText(str + " Fail");
            ((CheckBox)findViewById(R.id.checkboxWRSSI)).setTextColor(Color.RED);

            if(ManualCheck)
            {
                m_Status = WLAN;
                TestErrorInfo("Test WLAN Error,再试一次?");
            }
            else
            {
                CallTestFunction(true);
            }
        }
    }

    private void StartBluetoothTest()
    {
        if(modefile.equalsIgnoreCase("PRODUCT")) {
//			mSpinner.setMessage("Bluetooth search...");
            mSpinner.setMessage("蓝牙 搜寻中...");
            mSpinner.show();
            if(!mAdapter.isEnabled())
                mAdapter.enable();

            mAdapter.startDiscovery();
        }else{
            mAdapter.disable();
            AutoCheck = true;
            if(ManualCheck)
                CheckAllTest(false);
            else
                CallTestFunction(true);
        }
    }

    private void StartLiveTVTest()
    {
        Intent it = new Intent("com.google.android.tv.intent.action.TV");
        it.setClassName("com.google.tv.player", "com.google.tv.player.PlayerActivity");
        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(it);
        //m_Status = LIVETV;
    }

    private void StartIRTest()
    {
        new AlertDialog.Builder(this)
        //.setIcon(android.R.drawable.btn_star)
        .setTitle("ASUSUITest")
//		.setMessage("Please use IR to press ok")
        .setMessage("请按遥控器上的“OK”键")
        //.setPositiveButton("OK",null)
        .setPositiveButton("OK",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                String str =(String) ((CheckBox)findViewById(R.id.checkboxIR)).getText();
                str = str.replace(" Fail", "");
                str = str.replace(" Test", "");

                AutoCheck = true;
                ((CheckBox)findViewById(R.id.checkboxIR)).setText(str + " Pass");
                ((CheckBox)findViewById(R.id.checkboxIR)).setTextColor(Color.BLUE);
                ((CheckBox)findViewById(R.id.checkboxIR)).setChecked(true);
                if(ManualCheck)
                    CheckAllTest(false);
                else
                    CallTestFunction(true);
            }
        })
        .show();

    }

    private void StartMCUVerTest() {
        Log.d(TAG,"Check MCU FW Version");
        String mcuver = getMCUVer();
        String resultstr = "MCU VER: " + mcuver;
        if(mcuverfile.equalsIgnoreCase(mcuver))
        {
            AutoCheck = true;
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setText(resultstr + " Pass");
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setTextColor(Color.BLUE);
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setChecked(true);
            if(ManualCheck)
                CheckAllTest(false);
            else
                CallTestFunction(true);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setText(resultstr + " Fail");
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setTextColor(Color.RED);

            TestErrorInfo("MCU版本错误 (实际值/期望值): "+ "(" + mcuver + "/" + mcuverfile + ")" +"\r\n再试一次?");
        }
    }

    private void StartIRBTest()
    {
        Log.d(TAG,"DoIRBTest:" + DoIRBTest());

        AlertMessage();
    }

    private void StartMacTest()
    {
        macstring = getMacAddress();
        String macstringTemp = macstring.replace(":", "");	//to ex:00E011223344
        Log.d(TAG,"test==macstringTemp="+macstringTemp);
        Log.d(TAG,"test==macbeg="+macbeg);
        Log.d(TAG,"test==macend="+macend);

        if(ManualCheck)
        {
//        	StartApkInstallTest();	////sonic for test
        	AlertMessage();
        	return;
        }

        if(modefile.equalsIgnoreCase("PCBA"))
        {
            ((CheckBox)findViewById(R.id.checkboxMac)).setText("MAC Pass");
            ((CheckBox)findViewById(R.id.checkboxMac)).setTextColor(Color.BLUE);
            ((CheckBox)findViewById(R.id.checkboxMac)).setChecked(true);
            CallTestFunction(true);
        }
        else
        {
            if ((macstringTemp.compareToIgnoreCase(macbeg) < 0) || (macstringTemp.compareToIgnoreCase(macend) > 0))
            {
                Log.d(TAG,"test==mac is not between macbeg and macend!");

                ((CheckBox)findViewById(R.id.checkboxMac)).setText("MAC Fail");

                ((CheckBox)findViewById(R.id.checkboxMac)).setTextColor(Color.RED);

                CallTestFunction(true);
            }
            else
            {
                AlertMessage();
//				CallTestFunction(true);
            }
        }
        return;
    }

    private void StartShareTest()
    {
        m_Status = SHARE;
        Intent it = new Intent("");
        it.setClassName("com.asus.oplay", "com.asus.oplay.filemanager.FileBrowserActivity");
        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(it);
    }

    private void StartBuildTest()
    {
        testtitle = (String)((CheckBox)findViewById(R.id.checkboxBuild)).getText();
        testtitle = testtitle.replace(" Fail", "");
        testtitle = testtitle.replace(" Test", "");

        if(buildfile.equalsIgnoreCase(android.os.Build.DISPLAY))
        {
            AutoCheck = true;
            ((CheckBox)findViewById(R.id.checkboxBuild)).setText(testtitle + " Pass");
            ((CheckBox)findViewById(R.id.checkboxBuild)).setTextColor(Color.BLUE);
            ((CheckBox)findViewById(R.id.checkboxBuild)).setChecked(true);
            if(ManualCheck)
                CheckAllTest(false);
            else
                CallTestFunction(true);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxBuild)).setText(testtitle + " Fail");
            ((CheckBox)findViewById(R.id.checkboxBuild)).setTextColor(Color.RED);

            TestErrorInfo("版本号错误:\r\n"+android.os.Build.DISPLAY+"\r\n再试一次?");
        }
    }

    private void AlertMessage()
    {
        String title = "";

        Log.d(TAG,"AlertMessage:"+Integer.toString(m_Status));

        switch(m_Status)
        {
        case USB:
            title = "USB OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxUSB);
            break;
        case VIDEO:
            title = "视频播放OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxVideo);
            break;
        case AUDIO:
            title = "音乐播放OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxAudio);
            break;
        case PHOTO:
            title = "照片播放OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxPhoto);
            break;
//		case LIVETV:
//			title = "Live TV OK?";
//			checkboxbutton = (CheckBox)findViewById(R.id.checkboxLivetv);
//			break;
//		case BLUETOOTH:
//			title = "Bluetooth OK?";
//			checkboxbutton = (CheckBox)findViewById(R.id.checkboxBluetooth);
//			break;
        case LAN:
            title = "有线网络OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxLan);
            break;
        case WLAN:
            title = "无线网络OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxWLan);
            break;
        case WRSSI:
            title = "WRSSI(Wifi信号强度) OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxWRSSI);
            break;
        case IR:
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxIR);
            break;
//		case IRB:
//			title = "IR Blaster OK?";
//			checkboxbutton = (CheckBox)findViewById(R.id.checkboxIRB);
//			break;
        case MAC:
            title = "Mac:\"" + macstring + "\" OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxMac);
            break;
        case SHARE:
            title = "Share(共享) OK?";
            checkboxbutton = (CheckBox)findViewById(R.id.checkboxShare);
            break;
        case  MCUVER:

            break;
        default:
            title = "error";
            checkboxbutton = null;
            return;
        }

        testtitle = (String) checkboxbutton.getText();
        testtitle = testtitle.replace(" Fail", "");
        testtitle = testtitle.replace(" Test", "");

        new AlertDialog.Builder(this)
        //.setIcon(android.R.drawable.btn_star)
        .setTitle("ASUSUITest")
        .setMessage(title)
        //.setPositiveButton("OK",null)
        .setPositiveButton("是",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //checkboxbutton.getText();
                AutoCheck = true;
                checkboxbutton.setText(testtitle + " Pass");
                checkboxbutton.setTextColor(Color.BLUE);
                checkboxbutton.setChecked(true);
                if(ManualCheck)
                    CheckAllTest(false);
                else
                    CallTestFunction(true);
            }
        })
        .setNegativeButton("否",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //checkboxbutton.getText();
                checkboxbutton.setText(testtitle + " Fail");
                checkboxbutton.setTextColor(Color.RED);

                if(ManualCheck)
                    CheckAllTest(false);
                else
                    CallTestFunction(true);
            }
        })
        .setNeutralButton("重测",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //checkboxbutton.getText();
                //checkboxbutton.setText(checkboxbutton.getText() + " Pass");
                //checkboxbutton.setTextColor(Color.BLUE);
                CallTestFunction(false);
            }
        })
        .show();
    }

    private void TestErrorInfo(String title)
    {
        new AlertDialog.Builder(this)
        .setTitle("ASUSUITest")
        .setMessage(title)
        .setPositiveButton("是",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                CallTestFunction(false);
            }
        })
        .setNegativeButton("否",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                if(ManualCheck)
                    CheckAllTest(false);
                else
                    CallTestFunction(true);
            }
        })
        .show();
    }

    private void ErrorMessage(String title)
    {
        Log.i(TAG,"ErrorMessage"+title);

        new AlertDialog.Builder(this)
        //.setIcon(android.R.drawable.btn_star)
        .setTitle("ASUSUITest")
        .setMessage(title)
        //.setPositiveButton("OK",null)
        .setPositiveButton("OK",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                mactivity.finish();
            }
        })
        .show();
    }

    private void CallTestFunction(boolean next)
    {
        if(next)
            m_Status++;

        Log.i(TAG,"CallTestFunction:"+Integer.toString(m_Status));

        switch(m_Status)
        {
        case VIDEO:
            StartVideoTest();
            break;
        case AUDIO:
            StartAudioTest();
            break;
        case PHOTO:
            StartPhotoTest();
            break;
        case LIVETV:
            StartLiveTVTest();
            break;
        case BLUETOOTH:
            StartBluetoothTest();
            break;
        case LAN:
            StartLanTest();
            break;
        case WLAN:
            StartWLanTest();
            break;
        case WRSSI:
            StartWRSSITest();
            break;
        case IR:
            StartIRTest();
            break;
        case IRB:
            StartIRBTest();
            break;
        case MAC:
            StartMacTest();
            break;
        case SHARE:
            StartShareTest();
            break;
        case USB:
            StartUSBTest();
            break;
        case BUILD:
            StartBuildTest();
            break;
        case MCUVER:
            StartMCUVerTest();
            break;
        case TESTFINISH:
            //			if(IsTestOK(GetLogcontent()))
            //				ErrorMessage("All Test Pass");
            //			else
            //				ErrorMessage("Test Error");
            CheckAllTest(false);
            break;
        default:
            ErrorMessage("Unknow error,Exit.");
            return;
        }
    }

    private boolean CheckAllTest(boolean bsavecall)
    {
        boolean breturn = true;

        if(((CheckBox)findViewById(R.id.checkboxUSB)).isChecked())
        {
            ((CheckBox)findViewById(R.id.checkboxUSB)).setEnabled(false);
            ((CheckBox)findViewById(R.id.checkboxUSB)).setFocusable(false);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxUSB)).setEnabled(true);
            ((CheckBox)findViewById(R.id.checkboxUSB)).setFocusable(true);
            breturn = false;
        }

        if(((CheckBox)findViewById(R.id.checkboxVideo)).isChecked())
        {
            ((CheckBox)findViewById(R.id.checkboxVideo)).setEnabled(false);
            ((CheckBox)findViewById(R.id.checkboxVideo)).setFocusable(false);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxVideo)).setEnabled(true);
            ((CheckBox)findViewById(R.id.checkboxVideo)).setFocusable(true);
            breturn = false;
        }

        //		if(((CheckBox)findViewById(R.id.checkboxAudio)).isChecked())
        //		{
        //			((CheckBox)findViewById(R.id.checkboxAudio)).setEnabled(false);
        //			((CheckBox)findViewById(R.id.checkboxAudio)).setFocusable(false);
        //		}
        //		else
        //		{
        //			((CheckBox)findViewById(R.id.checkboxAudio)).setEnabled(true);
        //			((CheckBox)findViewById(R.id.checkboxAudio)).setFocusable(true);
        //			breturn = false;
        //		}
        //
        //		if(((CheckBox)findViewById(R.id.checkboxPhoto)).isChecked())
        //		{
        //			((CheckBox)findViewById(R.id.checkboxPhoto)).setEnabled(false);
        //			((CheckBox)findViewById(R.id.checkboxPhoto)).setFocusable(false);
        //		}
        //		else
        //		{
        //			((CheckBox)findViewById(R.id.checkboxPhoto)).setEnabled(true);
        //			((CheckBox)findViewById(R.id.checkboxPhoto)).setFocusable(true);
        //			breturn = false;
        //		}

        if(modefile.equalsIgnoreCase("PRODUCT")) {

                if(((CheckBox)findViewById(R.id.checkboxBluetooth)).isChecked())
                {
                    ((CheckBox)findViewById(R.id.checkboxBluetooth)).setEnabled(false);
                    ((CheckBox)findViewById(R.id.checkboxBluetooth)).setFocusable(false);
                }
                else
                {
                    ((CheckBox)findViewById(R.id.checkboxBluetooth)).setEnabled(true);
                    ((CheckBox)findViewById(R.id.checkboxBluetooth)).setFocusable(true);
                    breturn = false;
                }
        }

        if(((CheckBox)findViewById(R.id.checkboxLan)).isChecked())
        {
            ((CheckBox)findViewById(R.id.checkboxLan)).setEnabled(false);
            ((CheckBox)findViewById(R.id.checkboxLan)).setFocusable(false);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxLan)).setEnabled(true);
            ((CheckBox)findViewById(R.id.checkboxLan)).setFocusable(true);
            breturn = false;
        }

        if(((CheckBox)findViewById(R.id.checkboxIR)).isChecked())
        {
            ((CheckBox)findViewById(R.id.checkboxIR)).setEnabled(false);
            ((CheckBox)findViewById(R.id.checkboxIR)).setFocusable(false);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxIR)).setEnabled(true);
            ((CheckBox)findViewById(R.id.checkboxIR)).setFocusable(true);
            breturn = false;
        }


        if(((CheckBox)findViewById(R.id.checkboxBuild)).isChecked())
        {
            ((CheckBox)findViewById(R.id.checkboxBuild)).setEnabled(false);
            ((CheckBox)findViewById(R.id.checkboxBuild)).setFocusable(false);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxBuild)).setEnabled(true);
            ((CheckBox)findViewById(R.id.checkboxBuild)).setFocusable(true);
            breturn = false;
        }

        if(((CheckBox)findViewById(R.id.checkboxMCUVER)).isChecked())
        {
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setEnabled(false);
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setFocusable(false);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setEnabled(true);
            ((CheckBox)findViewById(R.id.checkboxMCUVER)).setFocusable(true);
            breturn = false;
        }

        if(((CheckBox)findViewById(R.id.checkboxMac)).isChecked())
        {
            ((CheckBox)findViewById(R.id.checkboxMac)).setEnabled(false);
            ((CheckBox)findViewById(R.id.checkboxMac)).setFocusable(false);
        }
        else
        {
            ((CheckBox)findViewById(R.id.checkboxMac)).setEnabled(true);
            ((CheckBox)findViewById(R.id.checkboxMac)).setFocusable(true);
            breturn = false;
        }

        ((Button)findViewById(R.id.buttonfinish)).setEnabled(true);
        ((Button)findViewById(R.id.buttonfinish)).setFocusable(true);

        if(breturn && !bsavecall)
        {
            SaveLogFile();
            //((Button)findViewById(R.id.buttonfinish)).callOnClick();
            ErrorMessage("All Pass !");
        }

        return breturn;

    }

    private String GetLogcontent()
    {
        String str;
        str = //((CheckBox)findViewById(R.id.checkboxVideo)).getText() + "\r\n"
                //+((CheckBox)findViewById(R.id.checkboxAudio)).getText() + "\r\n"
                //+((CheckBox)findViewById(R.id.checkboxPhoto)).getText() + "\r\n"
                ((CheckBox)findViewById(R.id.checkboxUSB)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxLan)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxWLan)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxWRSSI)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxBluetooth)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxLivetv)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxIR)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxIRB)).getText() + "\r\n"
                //+((CheckBox)findViewById(R.id.checkboxShare)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxMac)).getText() + "\r\n"
                +((CheckBox)findViewById(R.id.checkboxBuild)).getText() + "\r\n";

        return str;
    }

    //	private boolean IsTestOK()
    //	{
    //		int ipos = str.indexOf("Fail");
    //		int ipos1 = str.indexOf("Test");
    //
    //		if(ipos == -1 && ipos1 == -1)
    //			return true;
    //		else
    //			return false;
    //	}

    private void SaveLogFile()
    {
        File fileusb = new File(usblog);
        if(fileusb == null || !fileusb.exists())
            return;

        String filename;
        if(macstring == null)
            macstring = getMacAddress();
        if(macstring == null)
            filename = "mac-unknow-";
        else
        {
            Log.i(TAG,"mac:"+macstring);
            macstring = macstring.replace(":", "");
            filename = "mac-"+macstring+"-";
        }

        //SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd   hh:mm:ss");
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy:MM:dd:hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());

        if(date == null)
            filename = filename+"date-unknow";
        else
        {
            Log.i(TAG,"date:"+date);
            date = date.replace(":", "");
            filename = filename+date;
        }

        String logcontent = GetLogcontent();
        String logcat = "";
        File fileok = new File(usblog+"GTVLog/OK");
        File fileerror = new File(usblog+"GTVLog/Error");
        File file,filelog;// = new File(fileok,filename);
        //if(IsTestOK(GetLogcontent()))
        if(CheckAllTest(true))
        {
            Log.i(TAG,"OK LogFile:"+filename);
            file = new File(fileok,filename);
            filelog = new File(fileok,filename+"logcat");
        }
        else
        {
            Log.i(TAG,"Error LogFile:"+filename);
            file = new File(fileerror,filename);
            filelog = new File(fileerror,filename+"logcat");
        }

        try {
            Process process = Runtime.getRuntime().exec("logcat -d");
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            String line;
            //StringBuilder log = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                logcat = logcat + line + "\r\n";
            }
        } catch (IOException e) {
        }

        try {
            FileOutputStream fos,fos1;
            fos = new FileOutputStream(file);
            fos.write(logcontent.getBytes());
            fos.close();

            fos1 = new FileOutputStream(filelog);
            fos1.write(logcat.getBytes());
            fos1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//		Log.d(TAG,"logcat -d > " + filelog);
//		try {
//			Process process = Runtime.getRuntime().exec("logcat -d");
//		      BufferedReader bufferedReader = new BufferedReader(
//		      new InputStreamReader(process.getInputStream()));
//
//		      StringBuilder log=new StringBuilder();
//		      String line;
//		      while ((line = bufferedReader.readLine()) != null) {
//		        log.append(line);
//		      }
////            Process p;
////            //p = Runtime.getRuntime().exec("logcat -d > " + filelog);
////            p = Runtime.getRuntime().exec("logcat -d > /mnt/usbdrive/usb2.1/GTVLog/Error/test");
////            //p = Runtime.getRuntime().exec("touch " + filelog);
////            p.waitFor();
////            String line;
////            InputStreamReader ir = new InputStreamReader(p.getInputStream());
////            BufferedReader input = new BufferedReader(ir);
////            while ((line = input.readLine()) != null) {
////  	    	  Log.d(TAG,"1111:" + line);
//            //string = input.readLine();
//        } catch (IOException e) {
//        }
    }

    private void DisableAll()
    {
        ((CheckBox)findViewById(R.id.checkboxVideo)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxAudio)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxPhoto)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxLivetv)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxBluetooth)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxLan)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxWLan)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxWRSSI)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxIR)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxIRB)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxShare)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxMac)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxUSB)).setEnabled(false);
        ((CheckBox)findViewById(R.id.checkboxBuild)).setEnabled(false);
        ((Button)findViewById(R.id.buttonfinish)).setEnabled(false);

        ((CheckBox)findViewById(R.id.checkboxVideo)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxAudio)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxPhoto)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxLivetv)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxBluetooth)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxLan)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxWLan)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxWRSSI)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxIR)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxIRB)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxShare)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxMac)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxUSB)).setFocusable(false);
        ((CheckBox)findViewById(R.id.checkboxBuild)).setFocusable(false);
        ((Button)findViewById(R.id.buttonfinish)).setFocusable(false);
    }

    private boolean CheckLogFileSystem()
    {
        Log.i(TAG,"CheckLogFileSystem");

        if(usblog == null || usblog.equalsIgnoreCase("") == true)
        {
            ErrorMessage("Error Media USB!");
            return false;
        }

        Log.i(TAG,"CheckLogFileSystem:"+usblog);

        File file = new File(usblog+"GTVLog");
        File fileok = new File(usblog+"GTVLog/OK");
        File fileerror = new File(usblog+"GTVLog/Error");

        Log.d(TAG,usblog+"GTVLog");

        if(!file.exists())
            file.mkdir();

        if(!fileok.exists())
            fileok.mkdir();

        if(!fileerror.exists())
            fileerror.mkdir();

        if(file.exists() && fileok.exists() && fileerror.exists())
        {
        }
        else
        {
            ErrorMessage("Unable to create the log folder,Exit.");
            return false;
        }

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy:MM:dd:hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        date = date.replace(":", "");
        String strfiletest = "test";
        if(date != null)
            strfiletest = date;
        File filetest = new File(usblog+"GTVLog/"+strfiletest);
        filetest.mkdir();
        if(filetest.exists())
        {
            filetest.delete();
        }
        else
        {
            ErrorMessage("Unable to create file,Exit.");
            return false;
        }

        return true;
    }

    private boolean CheckMediaFileSystem()
    {
        Log.i(TAG,"CheckMediaFileSystem");

        if(usbmedia == null || usbmedia.equalsIgnoreCase("") == true)
        {
            ErrorMessage("Error Media USB!");
            return false;
        }

        Log.i(TAG,"CheckMediaFileSystem usbmedia:"+usbmedia);

        File file = new File(usbmedia+".factorymode_media/.mediausb");
        if(!file.exists())
        {
            ErrorMessage("No media usb file,Exit.");
            return false;
        }
        else
        {
            String str="";
            try {
                FileInputStream fos;
                fos = new FileInputStream(file);
                byte [] buffer = new byte[fos.available()];
                fos.read(buffer);
                str = EncodingUtils.getString(buffer, "UTF-8");
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                Log.e(TAG,"CheckMediaFileSystem FileNotFoundException");
                e.printStackTrace();
            } catch (IOException e) {
                Log.e(TAG,"CheckMediaFileSystem IOException");
                e.printStackTrace();
            }
            if(str == null || str.equalsIgnoreCase(""))
            {
                ErrorMessage("Read media usb file error,Exit.");
                return false;
            }
            else
            {
                Log.i(TAG,"ALL:"+str);

                if(str.indexOf("VIDEO:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("VIDEO:")) != -1)
                        videofile = str.substring(str.indexOf("VIDEO:")+6, str.indexOf("\n",str.indexOf("VIDEO:")));
                    else
                        videofile = str.substring(str.indexOf("VIDEO:")+6);
                }
                videofile = videofile.trim();

                if(videofile.equalsIgnoreCase(""))
                {
                    videofile = "mp4.mp4";
                    Log.i(TAG,"Get videofile error");
                }
                Log.i(TAG,videofile);

                if(str.indexOf("AUDIO:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("AUDIO:")) != -1)
                        audiofile = str.substring(str.indexOf("AUDIO:")+6, str.indexOf("\n",str.indexOf("AUDIO:")));
                    else
                        audiofile = str.substring(str.indexOf("AUDIO:")+6);
                }

                audiofile = audiofile.trim();

                if(audiofile.equalsIgnoreCase(""))
                {
                    audiofile = "mp3.mp3";
                    Log.i(TAG,"Get audiofile error");
                }
                Log.i(TAG,audiofile);

                if(str.indexOf("PHOTO:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("PHOTO:")) != -1)
                        photofile = str.substring(str.indexOf("PHOTO:")+6, str.indexOf("\n",str.indexOf("PHOTO:")));
                    else
                        photofile = str.substring(str.indexOf("PHOTO:")+6);
                }
                photofile = photofile.trim();

                if(photofile.equalsIgnoreCase(""))
                {
                    photofile = "jpg.jpg";
                    Log.i(TAG,"Get photofile error");
                }
                Log.i(TAG,photofile);

                //if(str.indexOf("LAN:") != -1)
                //	lanfile = str.substring(str.indexOf("LAN:")+4, str.indexOf("\n",str.indexOf("LAN:")));

                if(str.indexOf("WLAN:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("WLAN:")) != -1)
                        wlanfile = str.substring(str.indexOf("WLAN:")+5, str.indexOf("\n",str.indexOf("WLAN:")));
                    else
                        wlanfile = str.substring(str.indexOf("WLAN:")+5);
                }
                wlanfile = wlanfile.trim();
                if(wlanfile.equalsIgnoreCase(""))
                {
                    wlanfile = "test";
                    Log.i(TAG,"Get wlanfile error");
                }
                Log.i(TAG,wlanfile);

                if(str.indexOf("BLUETOOTH:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("BLUETOOTH:")) != -1)
                        btfile = str.substring(str.indexOf("BLUETOOTH:")+10, str.indexOf("\n",str.indexOf("BLUETOOTH:")));
                    else
                        btfile = str.substring(str.indexOf("BLUETOOTH:")+10);
                }
                btfile = btfile.trim();
                if(btfile.equalsIgnoreCase(""))
                {
                    btfile = "00:11:22:33:44:55";
                    Log.i(TAG,"Get btfile error");
                }
                Log.i(TAG,btfile);

                if(str.indexOf("STRENGTH:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("STRENGTH:")) != -1)
                        wifistrength = str.substring(str.indexOf("STRENGTH:")+9, str.indexOf("\n",str.indexOf("STRENGTH:")));
                    else
                        wifistrength = str.substring(str.indexOf("STRENGTH:")+9);
                }
                wifistrength = wifistrength.trim();
                if(wifistrength.equalsIgnoreCase(""))
                {
                    wifistrength = "95";
                    Log.i(TAG,"Get wifistrength error");
                }
                Log.i(TAG,wifistrength);

                if(str.indexOf("BUILD:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("BUILD:")) != -1)
                        buildfile = str.substring(str.indexOf("BUILD:")+6, str.indexOf("\n",str.indexOf("BUILD:")));
                    else
                        buildfile = str.substring(str.indexOf("BUILD:")+6);
                }
                buildfile = buildfile.trim();
                if(buildfile.equalsIgnoreCase(""))
                {
                    buildfile = "test";
                    Log.i(TAG,"Get buildfile error");
                }
                Log.i(TAG,buildfile);

                if(str.indexOf("MCUVER:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("MCUVER:")) != -1)
                        mcuverfile = str.substring(str.indexOf("MCUVER:")+7, str.indexOf("\n",str.indexOf("MCUVER:")));
                    else
                        mcuverfile = str.substring(str.indexOf("MCUVER:")+7);
                }
                mcuverfile = mcuverfile.trim();
                if(buildfile.equalsIgnoreCase(""))
                {
                    mcuverfile = "";
                    Log.i(TAG,"Get mcuverfile error");
                }
                Log.i(TAG,mcuverfile);

                if(str.indexOf("MACBEG:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("MACBEG:")) != -1)
                        macbeg = str.substring(str.indexOf("MACBEG:")+7, str.indexOf("\n",str.indexOf("MACBEG:")));
                    else
                        macbeg = str.substring(str.indexOf("MACBEG:")+7);
                }
                macbeg = macbeg.trim();
                if(macbeg.equalsIgnoreCase(""))
                {
                    macbeg = "000000000000";
                    Log.i(TAG,"获取MAC起始地址 error");
                }
                Log.i(TAG,macbeg);

                if(str.indexOf("MACEND:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("MACEND:")) != -1)
                        macend = str.substring(str.indexOf("MACEND:")+7, str.indexOf("\n",str.indexOf("MACEND:")));
                    else
                        macend = str.substring(str.indexOf("MACEND:")+7);
                }
                macend = macend.trim();
                if(macend.equalsIgnoreCase(""))
                {
                    macend = "000000000000";
                    Log.i(TAG,"获取MAC起始地址 error");
                }
                Log.i(TAG,macend);
                
//                ////sonic for test
//                if(str.indexOf("APK:") != -1)
//                {
//                    if(str.indexOf("\n",str.indexOf("APK:")) != -1)
//                    	apkfile = str.substring(str.indexOf("APK:")+4, str.indexOf("\n",str.indexOf("APK:")));
//                    else
//                    	apkfile = str.substring(str.indexOf("APK:")+4);
//                }
//                apkfile = apkfile.trim();
//                if(apkfile.equalsIgnoreCase(""))
//                {
//                	apkfile = "apk.apk";
//                    Log.i(TAG,"获取APK安装包文件 error");
//                }
//                Log.i(TAG,apkfile);
//                ////sonic for test
                return true;
            }
        }
    }


    private boolean CheckConfigFileSystem()
    {
        Log.i(TAG,"CheckConfigFileSystem");

        if(usbconfig == null || usbconfig.equalsIgnoreCase("") == true)
        {
            ErrorMessage("Error Config USB!");
            return false;
        }

        Log.i(TAG,"CheckConfigFileSystem usbconfig:"+usbconfig);

        File file = new File(usbconfig+".factorymode_config/.configusb");
        if(!file.exists())
        {
            ErrorMessage("No config usb file,Exit.");
            return false;
        }
        else
        {
            String str="";
            try {
                FileInputStream fos;
                fos = new FileInputStream(file);
                byte [] buffer = new byte[fos.available()];
                fos.read(buffer);
                str = EncodingUtils.getString(buffer, "UTF-8");
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                Log.e(TAG,"CheckConfigFileSystem FileNotFoundException");
                e.printStackTrace();
            } catch (IOException e) {
                Log.e(TAG,"CheckConfigFileSystem IOException");
                e.printStackTrace();
            }
            if(str == null || str.equalsIgnoreCase(""))
            {
                ErrorMessage("Read config usb file error,Exit.");
                return false;
            }
            else
            {
                Log.i(TAG,"ALL:"+str);

                if(str.indexOf("MODE:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("MODE:")) != -1)
                        modefile = str.substring(str.indexOf("MODE:")+5, str.indexOf("\n",str.indexOf("MODE:")));
                    else
                        modefile = str.substring(str.indexOf("MODE:")+5);
                }
                if(modefile.equalsIgnoreCase(""))
                {
                    modefile = "PCBA";
                    Log.i(TAG,"Get modefile error");
                }
                Log.i(TAG,"Facotry Test Mode: " + modefile);

                if(!modefile.equalsIgnoreCase("PRODUCT")) {
                    ((CheckBox)findViewById(R.id.checkboxBluetooth)).setVisibility(View.INVISIBLE);
                }

                return true;
            }
        }
    }

    private static String loadFileAsString(String filePath) throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

    /*
     * Get the STB MacAddress
     */
    private String getMacAddress()
    {
        try {
//            return loadFileAsString("/sys/class/net/eth0/address")
//                    .toUpperCase().substring(0, 17);
            
            return loadFileAsString("/system/testmac")
                    .toUpperCase().substring(0, 17);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private String getMCUVer() {
        String mcuver = SystemProperties.get("persist.gamebox.mcufwver", "0");
        return mcuver;
    }
}
